package com.demo.dao.impl;

import com.demo.dao.IUserDao;
import com.demo.pojo.User;

import java.sql.*;

public class UserDaoImpl implements IUserDao {
    public User login(String name, String password)throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java2", "root", "123456");
        PreparedStatement stmt = conn.prepareStatement("select * from user where account = ? and password = ?");
        stmt.setString(1, name);
        stmt.setString(2, password);
        // 执行
        ResultSet rs = stmt.executeQuery();
        User user = null;
        if(rs.next()){
            user = new User();
            user.setId(rs.getInt("id"));
            user.setAccount(rs.getString("account"));
            user.setPassword(rs.getString("password"));
            user.setName(rs.getString("name"));
            user.setSex(rs.getString("sex"));
            user.setAddress(rs.getString("address"));
        }
        rs.close();
        stmt.close();
        conn.close();
        return user;
    }

    @Override
    public int register(User user) throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java2", "root", "123456");
        String sql = "insert into user values (null,?,?,?,?,?,?)";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, user.getAccount());
        stmt.setString(2, user.getPassword());
        stmt.setString(3, user.getName());
        stmt.setString(4, user.getSex());
        stmt.setString(5, user.getAddress());
        stmt.setString(6, user.getSalt());
        // 执行
        int x = stmt.executeUpdate();
        stmt.close();
        conn.close();
        return x;
    }
}
